<template>
	<view class="home">
		<!-- 通知 -->
		<view>
			<u-notice-bar :text="text1" mode="closable"></u-notice-bar>
		</view>
		<!-- 骨架屏 -->
		<view class="skeleton" v-show="skeleton">
			<u-skeleton title="true" :loading="true" rows="5" :animate="true"></u-skeleton>
		</view>

		<!-- 用于包裹除骨架屏以外的东西 -->
		<view v-show="!skeleton">
			<!-- 个人信息 -->
			<view class="personBox">
				<!-- 用户名称 -->
				<view class="nameRow">
					<!-- 用户姓名 -->
					<view class="userName">
						{{userInfo.nickname||userInfo.username||userList.nickname||userList.username||"匿名用户"}}
						<!-- {{userList.nickname? `${userList.nickname}`:'匿名用户'}} -->
					</view>

					<!-- 用户个性签名 -->
					<!-- ||userList.usersign -->
					<view class="signature">
						{{storageUsersign||userList.usersign||'个性签名，可前往个人中心填写'}}
					</view>
				</view>

				<!-- 用户信息 -->
				<view class="infoBox">
					<view class="infoItem">
						<view>
							刷题进度:
						</view>
						<view class=".data">
							{{historyCount? `${historyCount}`:'0'}}/{{questionCount}}
						</view>
					</view>

					<view class="infoItem">
						<view>
							正确率:
						</view>
						<view class=".data">
							{{accuracyRate}}%
						</view>
					</view>
				</view>

				<view class="infoBox">
					<view class="infoItem">
						<view>
							目标院校:
						</view>
						<view class=".data">
							<!-- ||userList.targetUniversity -->
							{{storageTargetUniversity||userList.targetUniversity||"未填写目标院校"}}
						</view>
					</view>

					<view class="infoItem">
						<view>
							刷题数量:
						</view>
						<view class=".data">
							{{brushCount}}
						</view>
					</view>
				</view>

			</view>

			<!-- 功能组件 -->
			<view class="functionBox">
				<view class="functionItem" v-for="item in myFuction" :key="myFuction.fid"
					@click="goFunction(`${item.fid}`)">
					<view class="functionPic" :style="{backgroundImage:`url(${item.fPic})`}">

					</view>

					<view class="functionText">
						{{item.ftext}}
					</view>
				</view>
			</view>

			<!-- 刷题功能模块 -->
			<view class="questionsBox">
				<view class="functionItem" v-for="item in questionsList" :key="questionsList.qid"
					@click="goQuestionsTab(`${item.qid}`)">
					<view class="functionPic" :style="{backgroundImage:`url(${item.pic})`}">

					</view>

					<view class="functionText">
						{{item.text}}
					</view>
				</view>
			</view>

			<!-- 历史记录标题 -->
			<view class="history">
				历史记录
				<view class="historyMore">
					(仅显示前20条做题记录，更多请在我的-历史记录中查看)
				</view>
			</view>

			<!-- 历史记录 -->
			<view class="historyBox" v-for="historyList in historyList" :key="historyList._id">

				<view class="historyRow"
					@click="goQuestionsDetail(`${historyList.qOrder}`,`${historyList.subject_id}`,`${historyList.Chapterid}`)">
					<view class="historyTitle">
						{{historyList.subjectName}}
					</view>

					<view class="historyContent">
						{{historyList.ChapterName}}
					</view>
					—
					<view class="historyContent">
						第{{historyList.qOrder}}题
					</view>
				</view>
				<view class="historyDel"
					@click="historyDel(`${historyList._id}`,`${historyList.subject_id}`,`${historyList.Chapterid}`,)">
					<u-button size="small" type="primary" :plain="true" :hairline="true" text="删除">
					</u-button>

				</view>

			</view>
		</view>
		<!-- 顺序刷题的上拉框 -->
		<u-action-sheet :actions="sheetList" title="请选择科目" :closeOnClickOverlay="true" :closeOnClickAction="true"
			@close="closeSheet" @select="selectionSheet" :show="sheetStaic" round="16"></u-action-sheet>
	</view>



</template>

<script>
	import {
		store,
		mutations
	} from '@/uni_modules/uni-id-pages/common/store.js'
	const userInfo = uniCloud.importObject("userInfo", {
		customUI: true // 取消自动展示的交互提示界面
	}); //导入用户信息的云对象
	const questionFun = uniCloud.importObject("questionFun", {
		customUI: true
	});
	const db = uniCloud.database();

	export default {
		data() {
			return {

				sheetQid: 0, //用于记录sheet选择了哪个功能
				storageTargetUniversity: "", //缓存中的目标院校
				storageUsersign: "", //缓存中的个性签名
				questionCount: 0, //题库中题目总数
				userRight: 0, //用户正确题数
				accuracyRate: 0, //保存用户的正确率
				brushCount: 0, //保存用户的刷题数量
				historyCount: 0, //保存用户历史记录里的数量
				skeleton: true, //数据加载完毕后取消骨架屏
				backRefresh: false, //用于从上一级页面返回时刷新数据
				// uid:""//记录当前用户uid
				userList: [], //保存用户数据
				text1: "免责声明：本小程序仅供毕设开发学习,使用无任何商业用途,如有侵权请联系我,邮箱：2571219609@qq.com",
				myFuction: [{
					fid: 1,
					fPic: 'https://7463-tcb-jt4xhf2yawry64k-6chab0059a75-1316606514.tcb.qcloud.la/我的收藏.png',
					ftext: "我的收藏"

				}, {
					fid: 2,
					fPic: 'https://7463-tcb-jt4xhf2yawry64k-6chab0059a75-1316606514.tcb.qcloud.la/我的错题.png',
					ftext: "我的错题"
				}, {
					fid: 3,
					fPic: 'https://7463-tcb-jt4xhf2yawry64k-6chab0059a75-1316606514.tcb.qcloud.la/刷题排名.png',
					ftext: "刷题排行"
				}, {
					fid: 4,
					fPic: 'https://7463-tcb-jt4xhf2yawry64k-6chab0059a75-1316606514.tcb.qcloud.la/联系我.png',
					ftext: "联系我",
				}],
				questionsList: [{
						qid: 0,
						pic: 'https://7463-tcb-jt4xhf2yawry64k-6chab0059a75-1316606514.tcb.qcloud.la/数据结构.png',
						text: "数据结构"
					}, {
						qid: 1,
						pic: 'https://7463-tcb-jt4xhf2yawry64k-6chab0059a75-1316606514.tcb.qcloud.la/操作系统.png',
						text: "操作系统"
					}, {
						qid: 2,
						pic: 'https://7463-tcb-jt4xhf2yawry64k-6chab0059a75-1316606514.tcb.qcloud.la/计算机网络.png',
						text: "计算机网络"
					}, {
						qid: 3,
						pic: 'https://7463-tcb-jt4xhf2yawry64k-6chab0059a75-1316606514.tcb.qcloud.la/组成原理.png',
						text: "组成原理"
					}, {
						qid: 4,
						pic: 'https://7463-tcb-jt4xhf2yawry64k-6chab0059a75-1316606514.tcb.qcloud.la/顺序刷题.png',
						text: "顺序刷题"
					}, {
						qid: 5,
						pic: 'https://7463-tcb-jt4xhf2yawry64k-6chab0059a75-1316606514.tcb.qcloud.la/随机刷题.png',
						text: "随机刷题"
					}, {
						qid: 6,
						pic: 'https://7463-tcb-jt4xhf2yawry64k-6chab0059a75-1316606514.tcb.qcloud.la/pic/考卷.png',
						text: "统考组卷"
					},{
						qid: 7,
						pic: 'https://7463-tcb-jt4xhf2yawry64k-6chab0059a75-1316606514.tcb.qcloud.la/自主组卷.png',
						text: "自主组卷"
					}
				],
				sheetList: [ //上拉框list
					{
						name: '数据结构',
						fontSize: '16',
						type: 0
					},
					{
						name: '操作系统',
						fontSize: '16',
						type: 1

					}, {
						name: '计算机网络',
						fontSize: '16',
						type: 2

					}, {
						name: '组成原理',
						fontSize: '16',
						type: 3

					},
				],
				sheetStaic: false, //sheet显示状态

				historyList: [] //保存用户历史记录数据

			}
		},
		onShow() {
			// console.log("111");
			var pages = getCurrentPages(); // 获取当前页面栈
			var currentPage = pages[pages.length - 1]; // 当前页面
			if (currentPage.data.backRefresh) {
				currentPage.data.backRefresh = false;
				this.getHistoryData();
				uni.pageScrollTo({
					scrollTop: 0,
					duration: 0
				})
			}
			if (uni.getStorageInfoSync("user-targetUniversity") || uni.getStorageSync("user-usersign")) {
				// this.storageTargetUniversity = uni.getStorageInfoSync("user-targetUniversity")
				this.storageTargetUniversity = uni.getStorageSync("user-targetUniversity")
				this.storageUsersign = uni.getStorageSync("user-usersign")
				console.log("storageTargetUniversity", this.storageUsersign);
			}
		},
		onHide() {
			// console.log("222");
			// this.decideUserBrushes();
		},
		onReady() {
			this.getUser();
		},

		onLoad() {

		},
		computed: {
			userInfo() {
				return store.userInfo;
			},
			hasLogin() {
				return store.hasLogin
			}

		},
		methods: {
			// 获取用户信息
			async getUser() {
				// try{
				const uid = uniCloud.getCurrentUserInfo().uid;
				const userData = await userInfo.getUserData(uid);
				console.log("userData", userData);
				this.userList = userData.data[0];
				this.ifNickNameNull();
				console.log("用户数据", this.userList);
				this.getHistoryData();
				this.getQuestionCount(uid);
				this.saveStoryUser();
				this.uid = this.userList._id;
				this.skeleton = false;

			},
			//获取刷题量正确率
			async getUserBrushes(uid) {
				const userBrushesData = userInfo.getUserBrushesData(uid);
				// console.log("userBrushesData",userBrushesData);
				userBrushesData.then(res => {
					// console.log("userBrushesData",res.data.length);
					if (res.data.length == 0) {
						return;
					} else {
						userBrushesData.then(res => {
							this.brushCount = parseInt(res.data[0].brushProgress);
							this.userRight = parseInt(res.data[0].accuracyNum);
							const brushCount = parseInt(res.data[0].brushProgress);
							const userRight = parseInt(res.data[0].accuracyNum);
							// this.accuracyRate = this.userRight / this.questionCount;
							this.accuracyRate = userRight / brushCount;
							console.log("this.accuracyRate", this.accuracyRate);
							this.accuracyRate = this.accuracyRate.toFixed(2) * 100;
							this.saveUserBrushes();
						})
					}
				}).catch(() => {
					uni.showToast({
						title: "获取刷题量失败",
						icon: 'error'
					})
				})


			},

			//将正确率刷题数保存到本地缓存
			async saveUserBrushes() {
				try {
					uni.setStorageSync('brushCount', this.brushCount);
					uni.setStorageSync('accuracyRate', this.accuracyRate);
				} catch (e) {
					console.log("存储失败");
				}
			},


			// 历史记录删除
			async historyDel(hid) {
				uni.showModal({
					title: "删除提醒",
					content: "删除该题历史记录将删除该题的回答记录和刷题进度，该题将重新作答！",
					success: (res => {
						try {
							if (res.confirm) {
								const delHistory = userInfo.delHistory(hid);
								delHistory.then(() => {
									this.getHistoryData();
									console.log("delHistory", delHistory);
								})

							}
						} catch (e) {
							//TODO handle the exception
							uni.showToast({
								title: "删除出错拉！",
								icon: 'error'
							})
						}
					})
				})
			},
			// 获取历史记录数据
			async getHistoryData() {
				const uid = this.userList._id;
				const UserHistoryData = await userInfo.getUserHistory(uid);
				console.log("UserHistoryData", UserHistoryData);
				this.historyCount = UserHistoryData.count;
				this.historyList = UserHistoryData.data;
				// this.getAccuracyRate(uid);
				this.getUserBrushes(uid);
				console.log("historyList", this.historyList);

			},
			//点击历史记录跳转
			goQuestionsDetail(qOrder, subject_id, chapterid) {
				uni.navigateTo({
					url: "/pages/questionDetail/questionDetail?uid=" + this.userList._id + "&qOrder=" + qOrder +
						"&cid=" + subject_id + "&chapterId=" + chapterid+"&mode="+"nomal"
				})
			},

			//获取题库题目总数
			getQuestionCount(uid) {
				db.collection("ds").count()
					.then(res => {
						this.questionCount = res.result.total;
					})

			},
			// 跳转功能区对应页面
			goFunction(fid) {
				if (fid == 2) {
					uni.navigateTo({
						url: "/pages/wrongQuestion/wrongQuestion"
					})

				} else if (fid == 4) {
					uni.navigateTo({
						url: "/pages/linkMe/linkMe?" + fid
					});
				} else {
					uni.showToast({
						title: "正在开发,很快就会实装~",
						icon: 'none'
					})
				}
			},

			//跳转科目对应Tab
			goQuestionsTab(qid) {
				if (qid <= 3) {
					uni.navigateTo({
						url: "/pages/questionsTab/questionsTab?qid=" + qid + "&uid=" + this.userList._id
					})
				} else if (qid == 4 || qid == 5) {
					this.sheetStaic = true;
					this.sheetQid = qid;
				} else if (qid == 6) {
					uni.showModal({
						title: "考试提醒",
						content: "考试将不会记录做题情况，一旦退出不可再次参加考试！答题会记录刷题数量。",
						success: (res => {
							try {
								if (res.confirm) {
									uni.navigateTo({
										url:"/pages/questionDetail/questionDetail?mode="+"exam"+ "&uid=" + this.userList._id
									})
								}
							} catch (e) {
								//TODO handle the exception
								uni.showToast({
									title: "考试提醒拉！",
									icon: 'error'
								})
							}
						})
					})
					
				} else if (qid == 7){
					uni.navigateTo({
						url:"/pages/diyExamIndex/diyExamIndex?uid="+ this.userList._id
					})
				}

			},
			//顺序刷题功能
			sequence(e) {

				console.log("she", this.uid);
				uni.navigateTo({
					url: "/pages/questionDetail/questionDetail?cid=" + e.type + "&uid=" + this.uid + "&mode=se"
				})
			},
			//随机刷题
			randomQuestion(e) {

				console.log("randomQuestion", e);
				uni.navigateTo({
					url: "/pages/questionDetail/questionDetail?cid=" + e.type + "&uid=" + this.uid + "&mode=random"
				})
			},
			//用于选择sheet的功能
			selectionSheet(e) {
				// this.sheetStaic = true;
				// console.log("sheet",e);
				if (this.sheetQid == 4) {
					this.sequence(e);
				} else if (this.sheetQid == 5) {
					this.randomQuestion(e);
				}

			},
			//关闭sheet
			closeSheet() {
				this.sheetStaic = false;
			},
			//如果是匿名用户就将id前几个给他
			async ifNickNameNull() {
				if (!this.userList.nickname) {
					const temp = "微信用户" + this.userList._id.slice(0, 8);
					this.userList.nickname = temp;
					console.log(temp);
					const updataNickName = db.collection("uni-id-users").where({
							_id: this.userList._id
						})
						.update({
							nickname: temp
						});
					// updataNickName.then(()=>{
					// 	this.userList.nickname = temp
					// 	console.log("temp",this.userList.nickname);
					// })
				}
			},
			//保存本地用户缓存
			async saveStoryUser() {
				uni.setStorageSync("user-targetUniversity", this.userList.targetUniversity);
				uni.setStorageSync("user-usersign", this.userList.usersign);

			}
		}
	}
</script>

<style lang="scss">
	$textSize: 28rpx;
	$radius: 16rpx;

	page {
		background-color: #F8F8F8;
	}

	view {
		box-sizing: border-box;
	}

	.skeleton {
		padding: 25rpx;
	}

	.personBox {
		// background-color: #85A9F0;
		background-image: linear-gradient(to bottom, #1F6ED4, #B9EDF8);
		margin: 12rpx;
		border-radius: $radius;
		display: flex;
		flex-direction: column;
		align-content: flex-start;
		padding: 12rpx 12rpx;
		backdrop-filter: blur(3px);
	}

	.nameRow {
		// display: flex;
		// justify-content: space-between;
		// align-items: center;
		padding-bottom: 12rpx;

		.userName {
			color: #333333;
			font-size: 42rpx;
			font-weight: bold;
		}

		.signature {
			color: #424242;
			font-size: $textSize;
			text-align: left;
			padding-left: 12rpx;
			padding-top: 4rpx;
		}
	}

	.infoBox {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding-left: 12rpx;
	}

	.infoItem {
		width: 50%;
		display: flex;
		align-items: center;
		text-align: left;
		white-space: nowrap;
		font-size: 28rpx;
		padding-bottom: 12rpx;

		view {
			display: flex;
			align-items: center;

		}

		.data {
			align-: center;
			padding: 0 6rpx;
		}
	}


	.functionBox {
		margin: 12rpx;
		border-radius: $radius;
		border: 2rpx solid #578AEF;
		background-color: #ffffff;
		display: flex;
	}

	.functionItem {
		width: 25%;
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 18rpx 0;

		.functionPic {
			width: 78rpx;
			height: 78rpx;
			background-size: 100% 100%;
			background-repeat: no-repeat;
		}
	}

	.questionsBox {
		margin: 12rpx;
		border-radius: $radius;
		background-color: #ffffff;
		display: flex;
		flex-wrap: wrap;

		.functionItem {
			width: 25%;
			display: flex;
			flex-direction: column;
			align-items: center;
			padding: 18rpx 0;

			.functionPic {
				width: 150rpx;
				height: 150rpx;
				background-size: 100% 100%;
				background-repeat: no-repeat;
			}
		}
	}

	.history {
		color: #333333;
		font-size: 32rpx;
		font-weight: bold;
		margin: 12rpx;
		padding-left: 24rpx;
		padding-top: 24rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;

		.historyMore {
			font-size: 22rpx;
			color: #424242;
		}
	}

	.historyBoxNone {
		display: none;
	}

	.historyBox {
		margin: 12rpx;
		border-radius: $radius;
		background-color: #ffffff;
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 18rpx 18rpx;
		border: 2rpx solid #85A9F0;

		.historyRow {
			display: flex;
			align-items: center;
			width: 75%;
		}

		.historyTitle {
			font-size: 32rpx;
			font-weight: bold;
			padding-right: 12rpx;
		}

		.historyContent {
			font-size: 28rpx;
		}

		.historyDel {
			padding-right: 18rpx;
		}
	}
</style>